﻿
var cod;
var tamLayout;
function pluginStart(codigo, align, witdhLayout) {
    addCSS(align);
    cod = codigo;
	tamLayout = witdhLayout;
    getDataServidor();

}

function montaElementos(cod) {
    $("#contentDatas").append("<form id='formBusca' method='post' action='http://localhost:56681/hoteisemfoz/sites' target='_blank'></form>");
    $("#formBusca").append("<input id='cdFornecedor' name='cdFornecedor' type='text' style='display:none' />");
	if (tamLayout != undefined && tamLayout != ""){
		$("#formBusca").append("<input id='tamLayout' name='tamLayout' type='text' style='display:none' />");
		$("#tamLayout").val(tamLayout);
	}
    $("#formBusca").append("<div class='div_datas'></div>");
    $("#cdFornecedor").val(cod);
	

    var meses = carregaMeses();
    var d = $("#dtServidor").text();
    d = d.split("/");
    var dataAtual = new Date((d[2] + "-" + d[1] + "-" + d[0]).replace(/-/g, "/"));

   
    for (var i = 0; i < 3; i++)
        $(".div_datas").append("<div class='topo_itens'></div>");

    //
    //div data de checkin:
    var item_1 = $(".div_datas .topo_itens:nth-child(1)");
    item_1.append("<img id='clr_checkin' src='http://localhost:56681/Content/igu/images/calendar.png' alt='Selecione uma data' />")
                  .append("<input id='ipt_dtcheckin' style='display:none;' type='text' />")
                  .append("<select busca='hotel' id='nrDiaCheckin' name='nrDiaCheckin'></select>")
                  .append("<select busca='hotel' id='nrMesCheckin' name='nrMesCheckin'>");

    $("#nrDiaCheckin").append("<option value=''>Dia</option>");
    for (var i = 1; i < 32; i++)
        $("#nrDiaCheckin").append("<option value='" + i + "'>" + ("0" + i).slice(-2) + "</option>");


    $("#nrMesCheckin").append("<option value=''>Mês</option>");
    var dtForCheckIn = new Date(d[2], parseInt(d[1]) - 1, d[0]);
    for (var i = 0; i < meses.length; i++) {
        $("#nrMesCheckin").append("<option value='" + ("0" + (dtForCheckIn.getMonth() + 1)).slice(-2) + "/" + dtForCheckIn.getFullYear() + "'>" + meses[dtForCheckIn.getMonth()] + "</option>");
        dtForCheckIn.setFullYear(dataAtual.getFullYear(), parseInt(d[1]) + i);
    }

    //
    //div data de checkout:
    var item_2 = $(".div_datas .topo_itens:nth-child(2)");
    item_2.append("<img id='clr_checkout' src='http://localhost:56681/Content/igu/images/calendar.png' alt='Selecione uma data' />")
                  .append("<input id='ipt_dtcheckout' style='display:none;' type='text' />")
                  .append("<select busca='hotel' id='nrDiaCheckout' name='nrDiaCheckout'></select>")
                  .append("<select busca='hotel' id='nrMesCheckout' name='nrMesCheckout'>");

    $("#nrDiaCheckout").append("<option value=''>Dia</option>");
    for (var i = 1; i < 32; i++)
        $("#nrDiaCheckout").append("<option value='" + i + "'>" + ("0" + i).slice(-2) + "</option>");

    $("#nrMesCheckout").append("<option value=''>Mês</option>");
    var dtForCheckout = new Date(d[2], parseInt(d[1]) - 1, d[0]);
    for (var i = 0; i < meses.length; i++) {
        $("#nrMesCheckout").append("<option value='" + ("0" + (dtForCheckout.getMonth() + 1)).slice(-2) + "/" + dtForCheckout.getFullYear() + "'>" + meses[dtForCheckout.getMonth()] + "</option>");
        dtForCheckout.setFullYear(dataAtual.getFullYear(), parseInt(d[1]) + i);
    }

    //
    //botão confirma
    var item_3 = $(".div_datas .topo_itens:nth-child(3)");
    item_3.append("<a href='javascript:void(0)' class='btninput' id='a_confirmardispo'>Confirmar disponibilidade</a>");
}

function carregaMeses() {
    var lstMeses = new Array();
    lstMeses.push("Janeiro");
    lstMeses.push("Fevereiro");
    lstMeses.push("Março");
    lstMeses.push("Abril");
    lstMeses.push("Maio");
    lstMeses.push("Junho");
    lstMeses.push("Julho");
    lstMeses.push("Agosto");
    lstMeses.push("Setembro");
    lstMeses.push("Outubro");
    lstMeses.push("Novembro");
    lstMeses.push("Dezembro");

    return lstMeses;
}

function getDataServidor() {
    $.ajaxSetup({
        async: false
    });

    $.ajax({
        url: "http://localhost:56681/Hotel/getDataServidor/",
        async: false,
        type: "GET",
        contentType: 'application/json, charset=utf-8',
        dataType: "jsonp",
        jsonp: 'callback',
        crossDomain: true,
        success: function (data) {
            if (data != "") {
                $("#contentDatas").append("<span id='dtServidor' style='display:none'>" + data.dataServidor + "</span>");
                montaElementos(cod);
                setupCalendar();
                setupElementos();
            }
            else
                alert('Erro ao recuperar a data do servidor');
        }
    });
}

function setupCalendar() {
    $('#ipt_dtcheckin').datepicker({
        defaultDate: "+1w",
        minDate: 0,
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: setDateHosp
    });

    if ($('#ipt_dtcheckout').val() != "") {
        $('#ipt_dtcheckin').datepicker("option", "maxDate", $('#ipt_dtcheckout').val());
    }
    if ($('#ipt_dtcheckin').val() != "") {
        $('#ipt_dtcheckout').datepicker("option", "minDate", $('#ipt_dtcheckin').val());
    }

    $('#clr_checkin').click(function () {
        $('#ipt_dtcheckin').datepicker('show');
    });


    $('#ipt_dtcheckout').datepicker({
        defaultDate: "+1w",
        minDate: 0,
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function (dateText, inst) {
            var dt = dateText.split('/');
            var n = parseInt(dt[0], 32);
            $('select[id=nrDiaCheckout][busca=hotel]').val(n.toString(32));
            $('select[id=nrMesCheckout][busca=hotel]').val(dt[1] + '/' + dt[2]);

            date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);
            $('#ipt_dtcheckin').datepicker("option", "maxDate", date);
        }
    });
    $('#clr_checkout').click(function () {
        $('#ipt_dtcheckout').datepicker('show');
    });


}

function setDateHosp(dateText, inst) {
    var dt = dateText.split('/');
    var n = parseInt(dt[0], 32);
          
    $('select[id=nrDiaCheckin][busca=hotel]').val(n.toString(32));
    $('select[id=nrMesCheckin][busca=hotel]').val(dt[1] + '/' + dt[2]);

    // últimos 3 parametros pra não cair no bug do horário de verão
    var d = new Date(parseInt(dt[2], 10), parseInt(dt[1], 10) - 1, parseInt(dt[0], 10), 12, 0, 0);
    
    d.setDate(d.getDate() + 1);
    $('select[id=nrDiaCheckout][busca=hotel]').val(d.getDate());
    
    var strMes = (d.getMonth() + 1).toString(32);
    if (strMes.length == 1)
        strMes = "0" + strMes;

    $('select[id=nrMesCheckout][busca=hotel]').val(strMes + '/' + d.getFullYear().toString());
    $('#ipt_dtcheckout').val(d.getDate().toString() + '/' + strMes + '/' + d.getFullYear().toString());

    $('#ipt_dtcheckout').datepicker("option", "minDate", dateText);
}


function setupElementos() {
    $("#a_confirmardispo").click(function () {
        if ($('#ipt_dtcheckin').val() == "" || $('#ipt_dtcheckout').val() == "") {
            alert("Informe a data de Check in e Check out");
            return false;
        }

        $(this).parents('#formBusca').submit();
    });

    $('select[id=nrDiaCheckin][busca=hotel]').change(function () {
        if ($(this).val() != "" && $('select[id=nrMesCheckin][busca=hotel]').val() != "") {
            $('#ipt_dtcheckin').val($(this).val() + '/' + $('select[id=nrMesCheckin][busca=hotel]').val());
            setDateHosp($('#ipt_dtcheckin').val(), null);
            $('#ipt_dtcheckout').datepicker("option", "minDate", $('#ipt_dtcheckin').val());
        }
    });

    $('select[id=nrMesCheckin][busca=hotel]').change(function () {
        if ($('select[id=nrDiaCheckin][busca=hotel]').val() != "" && $(this).val() != "") {
            $('#ipt_dtcheckin').val($('select[id=nrDiaCheckin][busca=hotel]').val() + '/' + $(this).val());
            setDateHosp($('#ipt_dtcheckin').val(), null);
            $('#ipt_dtcheckout').datepicker("option", "minDate", $('#ipt_dtcheckin').val());
        }
    });

    $('select[id=nrDiaCheckout][busca=hotel]').change(function () {
        if ($(this).val() != "" && $('select[id=nrMesCheckout][busca=hotel]').val() != "") {
            $('#ipt_dtcheckout').val($(this).val() + '/' + $('select[id=nrMesCheckout][busca=hotel]').val());
            $('#ipt_dtcheckin').datepicker("option", "maxDate", $('#ipt_dtcheckout').val());
        }
    });

    $('select[id=nrMesCheckout][busca=hotel]').change(function () {
        if ($('select[id=nrDiaCheckout][busca=hotel]').val() != "" && $(this).val() != "") {
            $('#ipt_dtcheckout').val($('select[id=nrDiaCheckout][busca=hotel]').val() + '/' + $(this).val());
            $('#ipt_dtcheckin').datepicker("option", "maxDate", $('#ipt_dtcheckout').val());
        }
    });
}


function addCSS(alinhamento) {
    var headConteudo = "";

    headConteudo += '<link href="http://localhost:56681/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />';
    headConteudo += '<link href="http://localhost:56681/Content/themes/base/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css" />';

    headConteudo += '<style type="text/css">';
    headConteudo += ".ui-datepicker { font-size: 12px; }";
    headConteudo += ".ui-widget-header {border-color: #999;background: #ccc none;color: #fff}";
    headConteudo += ".ui-widget-content {border-color: #777; background: #fff none; color: #777}";
    headConteudo += ".ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {border-color: #999;background: #eee none;color: #555;}";
    headConteudo += alinhamento == "vertical" ? cssVertical() : cssHorizontal();
    headConteudo += "</style>";

    $("head").append(headConteudo);
}

function cssHorizontal() {
    var codCSS = "";
    codCSS += "#contentDatas .div_datas {margin-bottom: 1px;padding-bottom: 7px;background-color: #eee;height: 23px;margin-left: 2px;margin-right: 8px;padding-left: 10px;padding-top: 5px;width:530px}";
    codCSS += "#contentDatas .topo_itens {float: left;margin-right: 10px}";
    codCSS += "#contentDatas select {position: relative;font-weight: bold;top: -5px}";
    codCSS += "#contentDatas .topo_itens a {font-family:arial;text-align: center;position: relative;top: 7px;font-size: 9px;font-weight: bold}";
    codCSS += ".btninput:hover {background: #444}";
    codCSS += ".btninput {background: none repeat scroll 0 0 #aaa;border: 2px solid white;color: #fff;font-size: 11px;padding: 4px 14px;text-decoration: none}";
    return codCSS;
}

function cssVertical() {
    var codCSS = "";
    codCSS += "#contentDatas .div_datas {margin-bottom: 1px;padding-bottom: 7px;background-color: #eee;height: 85px;margin-left: 2px;margin-right: 8px;padding-left: 10px;padding-top: 5px;width:185px}";
    codCSS += "#contentDatas .topo_itens {float: left;margin-right: 10px}";
    codCSS += "#contentDatas select {position: relative;font-weight: bold;top: -5px}";
    codCSS += "#contentDatas .topo_itens a {font-family:arial;text-align: center;position: relative;top: 7px;left: 7px;font-size: 9px;font-weight: bold}";
    codCSS += "#contentDatas .topo_itens a:hover {color:#ddd}";
    codCSS += ".btninput:hover {background: #444}";
    codCSS += ".btninput {background: none repeat scroll 0 0 #aaa;border: 2px solid white;color: #fff;font-size: 11px;padding: 4px 14px;text-decoration: none}";
    return codCSS;
}
